import logging

from django.views.generic import TemplateView
from django.conf import settings
from django.http import Http404


from solanum.apps.basic.models import BlogDump, Entry, Comment

class ModelView(TemplateView):
    model = None
    url_param_name = 'slug'
    model_param_name = 'name'

    def get_model_query_params(self, *args, **kwargs):
        params = [self.model.active==True]
        ident_params = self.get_ident_model_query_params()
        params.extend(ident_params)
        return params

    def get_ident_model_query_params(self):
        """
        Return query params that will limit query to specific object. Used internally by .get_queryset().

        requires correct values in view's 
         .url_param_name - name of expected param name
         .model_param_name - name of property to be queried

        Returns a list of params to be applied to model's .query():
        """
        ident = self.kwargs.get(self.url_param_name)
        if not ident:
            return []
        prop = getattr(self.model, self.model_param_name, None)
        if not prop:
            return []
        return [prop == ident,]


    def get_queryset(self):
        params = self.get_model_query_params()
        return self.model\
                    .query(*params)\
                    .order(-self.model.created)

    def get_context_data(self, **kwargs):
        context = super(ModelView, self).get_context_data(**kwargs)
        context['objects'] = self.get_queryset()
        return context

class SingleResult(ModelView):
    """
    Provide single object (or 404) for ModelView. An object will be available
    in template under 'object' key.
    """
    def get_queryset(self):
        query = super(SingleResult, self).get_queryset()
        val = query.fetch(1)
        if not val:
            raise Http404
        return val

    def get_context_data(self, **kwargs):
        context = super(SingleResult, self).get_context_data(**kwargs)
        context['object'] = context['objects'][0]
        return context



# specific views
class IndexView(ModelView):
    model = BlogDump
    template_name = 'index.html'
    
    def get_ident_model_query_params(self):
        return []



class BlogDumpView(SingleResult):
    model = BlogDump
    template_name = 'index-blogdump.html'
      
    def get_entries(self, blogdump):
        q = Entry.query(Entry.active==True,
                        parent=blogdump)\
                 .order(-Entry.created)
        return q

    def get_context_data(self, **kwargs):
        context = super(BlogDumpView, self).get_context_data(**kwargs)
        context['entries'] = self.get_entries(context['object'])
        return context
